#!/usr/bin/env python3

import json
import pymongo
import time
import http.client, urllib.request, urllib.parse, urllib.error, base64,urllib.response
from config import *
from multiprocessing import Pool

class get_micro_data(object):
    def __init__(self,university_name,offset):
        self.university_name = university_name
        self.university_paper_data_json = {
            "expr": "And(composite(AA.AfN=='" + self.university_name + "'),Y>2008)",
            "entities": []
        }
        self.offset = offset
    '''
    调用micro接口
    '''
    def use_micro_interface(self):
        headers = {
        # 3d50680d6f7f4e7b9bd07495d029fefd walker13698221841@163.com
        # e321e00f876b41989a89b56887161602  2448038829@qq.com
        # e763619381d74f74a4f5038f5cb5a141
    		'Ocp-Apim-Subscription-Key': '3d50680d6f7f4e7b9bd07495d029fefd',
    	}
        params = urllib.parse.urlencode({
    		'expr': "And(composite(AA.AfN=='" + self.university_name + "'),Y>2007)",
    		'model': 'latest',
    	    'count': '1000',
    	    'offset': self.offset,
    	    'orderby': 'Y',
    	    'attributes': 'Ti,Y,CC,ECC,AA.AuN,AA.AuId,AA.AfN,AA.AfId,AA.S,F.FN,F.FId,J.JN.J.JID,C.CN,C.CId',
    	})
        conn = http.client.HTTPSConnection('api.labs.cognitive.microsoft.com')
        conn.request("GET", "/academic/v1.0/evaluate?%s"%params,"",headers)
        #防止访问micro频率过高而访问失败，因此sleep(5)
        # time.sleep(10)
        response = conn.getresponse()
        if response.status == 200:
            university_paper_data_str = str(response.read(),encoding = "utf-8")
            conn.close()
            self.university_paper_data_json = json.loads(university_paper_data_str)
            university_paper_data = self.university_paper_data_json["entities"]
            print(len(university_paper_data))
            return university_paper_data,response.status

        else:
            conn.close()

            university_paper_data = self.university_paper_data_json["entities"]
            return university_paper_data,response.status
